<template> 
	<div class="container">
    <input type="text" v-model="keyword" placeholder="请输入城市名或拼音">
    <div 
      class="search-content" 
      ref="search"
      v-show="keyword"
      >
      <ul>
        <li 
          v-for="(item,index) of list" 
          class="search-item"
          @click="handleCityClick(item.name)"
          >{{item.name}}</li>
        <li class="search-item" v-if="hasNoData">没有找到匹配数据</li>
      </ul>
    </div>
      </div>
</template> 


<script> 
import Bscroll from 'better-scroll'
import { mapMutations } from 'vuex'
export default { 
  data () { 
    return { 
      keyword: "",
      list: [],
      timer: null
    }; 
  }, 
  props:{
    cities:Object
  },
  methods: { 
    handleCityClick(city){
      // this.$store.commit("changeCity",city)
      this.changeCity(city)
      // this.list=[]
      this.keyword=""
    },
    ...mapMutations(['changeCity'])
  },
  computed:{
    hasNoData(){
      return !this.list.length
    }
  },
  mounted(){
  // console.log(this.timer)
  this.scroll=new Bscroll(this.$refs.search)
  },
  watch:{
    keyword () {
      if(this.timer){
        clearTimeout(this.timer)
      }
      if(!this.keyword){
        this.list=[]
        return;
      }
      this.timer=setTimeout(()=>{
        const result=[];
        for(let i in this.cities){
          this.cities[i].forEach(item=>{
            if(item.spell.indexOf(this.keyword)>-1 || item.name.indexOf(this.keyword)>-1){
              result.push(item)
            }
          })
        }
        this.list=result;
      },100)
    }
  }


}; 
</script> 

<style scoped> 
.container{
  background: #00bcd4;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 40px;
  flex-direction: column;
}
input{
  width: 90%;
  height: 30px;
  text-align: center;
  font-family: "微软雅黑";
  box-sizing: border-box;
  padding: 10px;
}
.search-content{
  z-index: 1;
  color: white;
  background: #eee;
  position: absolute;
  left: 0;
  top: 80px;
  bottom: 0;
  right: 0;
  color: #666;
  overflow: hidden;
}
.search-item{
  line-height: 2em;
  padding-left: 20px;
  background: white;
}
</style> 